package com.course.server.service;


import com.course.server.domain.Chapter;
import com.course.server.domain.ChapterExample;
import com.course.server.dto.ChapterDto;
import com.course.server.dto.ChapterPageDto;
import com.course.server.mapper.ChapterMapper;
import com.course.server.utils.CopyUtil;
import com.course.server.utils.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 〈一句话功能简述>
 * 〈测试〉
 *
 * @Author metype
 * @Create 2021/5/26
 * @Since 1.0.0
 */
@Service
public class ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    public void list(ChapterPageDto chapterPageDto) {
        PageHelper.startPage(chapterPageDto.getPage(), chapterPageDto.getSize());
        ChapterExample chapterExample = new ChapterExample();
        // ChapterExample 只能使用一次,后面的会覆盖之前的操作.
        ChapterExample.Criteria chapterExampleCriteria = chapterExample.createCriteria();
        if (StringUtil.isNotEmpty(chapterPageDto.getCourseId())) {
            chapterExampleCriteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
        }
        List <Chapter> chapterList = chapterMapper.selectByExample(chapterExample);
        PageInfo <Chapter> pageInfo = new PageInfo <>(chapterList);
        chapterPageDto.setTotal(pageInfo.getTotal());
        List <ChapterDto> chapterDtoList = CopyUtil.copyList(chapterList, ChapterDto.class);
        chapterPageDto.setList(chapterDtoList);
    }

    public void save(ChapterDto chapterDto) {
        Chapter chapter = CopyUtil.copy(chapterDto, Chapter.class);
        if (StringUtil.isEmpty(chapterDto.getId())) {
            this.insert(chapter);
        } else {
            this.update(chapter);
        }
    }

    private void insert(Chapter chapter) {
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }

    private void update(Chapter chapter) {
        chapterMapper.updateByPrimaryKeySelective(chapter);
    }

    public int del(String id) {
       return chapterMapper.deleteByPrimaryKey(id);
    }

}